package com.talent.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.talent.web.enums.OrderStatus;
import com.talent.web.enums.PayType;
import com.talent.web.enums.ResponseEnum;
import com.talent.web.exception.TalentException;
import com.talent.web.mapper.TlOrderMapper;
import com.talent.web.model.entity.TlOrder;
import com.talent.web.service.ITlOrderService;
import com.talent.web.utils.OrderIdGenerator;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * @ClassName：TlOrderServiceImpl
 * @Author: hszhou
 * @Date: 2025/3/26 13:34
 * @Description: 必须描述类做什么事情, 实现什么功能
 */

@Service
@RequiredArgsConstructor
public class TlOrderServiceImpl extends ServiceImpl<TlOrderMapper, TlOrder> implements ITlOrderService {


    private final  OrderIdGenerator orderIdGenerator;
    @Override
    public TlOrder createOrder(TlOrder tlOrder) {
        String outTradeNo = orderIdGenerator.generate();
        tlOrder.setOutTradeNo(outTradeNo);
        tlOrder.setStatus(OrderStatus.UNPAID.getCode());
        tlOrder.setPrice(BigDecimal.valueOf(100));
        tlOrder.setCreateTime(LocalDateTime.now());
        save(tlOrder);
        return tlOrder;
    }

    @Override
    public void updateOrder(String outTradeNo, String tradeNo,
                            OrderStatus orderStatus,
                            PayType payType
                             ) {
        TlOrder tlOrder = selectOrderByOutTradeNo(outTradeNo);
        if(tlOrder == null){
            throw new TalentException(ResponseEnum.ORDER_NOT_EXIT);
        }
        tlOrder.setPayType(payType.getCode());
        tlOrder.setStatus(orderStatus.getCode());
        tlOrder.setTradeNo(tradeNo);
        tlOrder.setPayTime(LocalDateTime.now());
        tlOrder.setUpdateTime(LocalDateTime.now());
        this.updateById(tlOrder);
    }



    private TlOrder selectOrderByOutTradeNo(String outTradeNo){
        return this.getOne(new LambdaQueryWrapper<TlOrder>().eq(TlOrder::getOutTradeNo, outTradeNo));
    }
}
